package com.shujia.spark.core

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.rdd.RDD

object Demo8GroupByKey {
  def main(args: Array[String]): Unit = {

    val conf = new SparkConf()
    conf.setMaster("local")
    conf.setAppName("groupByKey")
    val sc = new SparkContext(conf)

    val linesRDD: RDD[String] = sc.textFile("data/students.txt")

    //转换成kv结构
    val kvRDD: RDD[(String, String)] = linesRDD.map(line => {
      val clazz: String = line.split(",").last
      (clazz, line)
    })

    /**
     * groupByKey: 按照key进行分组，将相同的key分到同一个reduce中
     * 只能用于kv结构的RDD上
     */
    val groupByKeyRDD: RDD[(String, Iterable[String])] = kvRDD.groupByKey()

    //计算班级的人数
    val clazzNumRDD: RDD[(String, Int)] = groupByKeyRDD.map {
      case (clazz: String, iter: Iterable[String]) =>
        val num: Int = iter.size
        (clazz, num)
    }

    clazzNumRDD.foreach(println)
  }

}
